import Vue from 'vue'
import Vuex from 'vuex'
import $api from "../config/api";

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		userInfo: uni.getStorageSync('userInfo') || {
		},
		token: uni.getStorageSync('token') || '',
		tabbarList: [
			{
				"text": "首页",
				"pagePath": "pages/index/index",
				"iconPath": "/static/tabbar/index.png",
				"selectedIconPath": "/static/tabbar/index-selected.png",
				customIcon: true,

			},
			{
				"text": "联系客服",
				"pagePath": "pages/service/service",
				"iconPath": "/static/tabbar/product.png",
				"selectedIconPath": "/static/tabbar/product-selected.png",
				customIcon: true,
			},

			{
				iconPath: "/static/tabbar/midButton_iconPath.png",
				selectedIconPath: "/static/tabbar/midButton_iconPath.png",
				text: "发布动态",
				midButton: true,
				customIcon: true,
			},
			{
				"text": "用户动态",
				"pagePath": "pages/userPost/list",
				"iconPath": "/static/tabbar/post.png",
				"selectedIconPath": "/static/tabbar/post-selected.png",
				customIcon: true,
			},
			{
				"text": "我的",
				"pagePath": "pages/mine/mine",
				"iconPath": "/static/tabbar/mine.png",
				"selectedIconPath": "/static/tabbar/mine-selected.png",
				customIcon: true,
			}
		]
	},
	getters: {
		userInfo: state => state.userInfo,
		token: state => state.token,
		tabbarList: state => state.tabbarList,
	},
	mutations: {
		SET_USERINFO(state, userInfo) {
			let _userInfo = {
				...userInfo
			}
			if (userInfo.store) {
				_userInfo.store_id = userInfo.store.id
			} else if (userInfo.storeUser) {
				_userInfo.store_id = userInfo.storeUser.store_id
			}
			console.log('_userInfo',_userInfo)
			uni.setStorageSync('userInfo', _userInfo)
			state.userInfo = _userInfo
		},
		SET_TOKEN(state, token) {
			uni.setStorageSync('token', token)
			state.token = token
		},
		LOGOUT(state) {
			state.userInfo = {}
			state.token = ''
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('token')
		}
	},
	actions: {
		getUserInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				if (state.userInfo.id) {
					$api.getUserInfo(state.userInfo.id).then(res => {
						uni.hideLoading()
						if (res) {
							commit('SET_USERINFO', res)
							resolve(res)
						} else {
							reject()
						}
					})
				} else {
					reject()
				}
			})
		},
		setUserInfo({ commit, state }, userInfo) {
			uni.showLoading()
			$api.updateUser(state.userInfo.id, {
				nickname: userInfo.nickname,
				avatar_url: userInfo.avatar_url,
				phone: userInfo.phone
			}).then(res => {
				commit('SET_USERINFO', userInfo)
			}).finally(() => {
				uni.hideLoading()
			})
		},
	}
})

export default store
